"use client";
import React, { useEffect, useRef, useState } from "react";
import { Button, Input, message, Image } from "antd";
import { SendOutlined, ExpandOutlined, DeleteOutlined } from "@ant-design/icons";
import { PageContainer } from "@ant-design/pro-components";
import { useSelector } from "react-redux";
import { RootState } from "@/stores";
import "./index.css";
import { chatMuitiStreamUsingPost, chatStreamUsingPost } from "@/api/dummyInterviewController";
import ImageUpload from "@/components/ImageUpload";

/**
 * AI 模拟面试页面
 * @constructor
 */
export default function Interview() {
  const loginUser = useSelector((state: RootState) => state.loginUser);
  const [inputValue, setInputValue] = useState<string>("");
  const [chatHistory, setChatHistory] = useState<Array<{ role: "user" | "ai"; content: string; imageUrl?: string }>>([]);
  const [interviewId, setInterviewId] = useState<number>(0);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [currentTypingMessage, setCurrentTypingMessage] = useState<string>("");
  const [uploadedImageUrl, setUploadedImageUrl] = useState<string | null>(null);
  const [previewImage, setPreviewImage] = useState<string | null>(null);
  const chatContainerRef = useRef<HTMLDivElement>(null);
  const [isTyping, setIsTyping] = useState<boolean>(false);

  // 初始化聊天室 ID
  useEffect(() => {
    // 生成一个随机的聊天室 ID
    const randomId = Math.floor(Math.random() * 1000000);
    setInterviewId(randomId);
    
    // 添加 AI 的欢迎消息 - 只添加一次
    setChatHistory(prev => {
      // 检查是否已经有欢迎消息，避免React 18 Strict Mode下useEffect执行两次导致的重复消息
      if (prev.length === 0) {
        return [
          ...prev,
          {
            role: "ai",
            content: "你好！我是你的 AI 面试官，请问你想面试什么岗位？",
          },
        ];
      }
      return prev;
    });

    console.log("Interview component initialized with ID:", randomId);
  }, []);

  // 自动滚动到底部
  useEffect(() => {
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
    }
  }, [chatHistory, currentTypingMessage]);
  
  // 监控状态变化，便于调试
  useEffect(() => {
    console.log("Chat history updated:", chatHistory);
  }, [chatHistory]);
  
  useEffect(() => {
    console.log("Loading state:", isLoading);
  }, [isLoading]);

  // 处理图片上传完成
  const handleImageUpload = (url: string) => {
    setUploadedImageUrl(url);
    setPreviewImage(url);
  };
  
  // 处理图片删除
  const handleImageRemove = () => {
    setUploadedImageUrl(null);
    setPreviewImage(null);
  };

  // 发送消息
  const handleSendMessage = async () => {
    if (!inputValue.trim() && !uploadedImageUrl) {
      message.warning("请输入消息或上传图片");
      return;
    }

    try {
      const userMessage = inputValue.trim();
      let imagePath = uploadedImageUrl || "";
      
      console.log("准备发送消息:", userMessage, "是否有图片:", !!uploadedImageUrl);
      
      // 添加用户消息到聊天历史，包含图片URL
      console.log("添加用户消息到聊天历史:", { 
        content: userMessage || "发送了一张图片",
        imageUrl: imagePath || undefined
      });
      
      setChatHistory((prev) => [
        ...prev,
        { 
          role: "user", 
          content: userMessage || "发送了一张图片",
          imageUrl: imagePath || undefined
        },
      ]);
      
      // 清空输入框和图片
      setInputValue("");
      setUploadedImageUrl(null);
      setPreviewImage(null);
      
      setIsLoading(true);
      message.loading({ content: 'AI思考中...', key: 'ai-thinking' });
      
      // 重置当前打字内容并激活打字状态
      setCurrentTypingMessage("");
      setIsTyping(true);

      // 创建EventSource连接
      let eventSourceUrl;
      if (imagePath) {
        console.log("使用多模态API (带图片)");
        eventSourceUrl = `/api/sse?path=${encodeURIComponent("/api/dummyinterview/chatByMuitiStream")}&interviewId=${interviewId}&query=${encodeURIComponent(userMessage)}&imagePath=${encodeURIComponent(imagePath)}`;
      } else {
        console.log("使用纯文本API");
        eventSourceUrl = `/api/sse?path=${encodeURIComponent("/api/dummyinterview/chatStream")}&interviewId=${interviewId}&query=${encodeURIComponent(userMessage)}`;
      }

      console.log("创建SSE连接:", eventSourceUrl);
      
      // 创建 EventSource 连接
      const eventSource = new EventSource(eventSourceUrl);
      
      // 处理连接打开
      eventSource.onopen = () => {
        console.log("SSE连接打开成功");
        message.destroy('ai-thinking');
      };
      
      // 用于累积完整响应的变量
      let fullResponse = "";
      
      // 处理消息事件
      eventSource.onmessage = (event) => {
        if (!event.data) return;
        
        const data = event.data;
        
        if (data && data !== '[DONE]') {
          // 累加到完整响应中
          fullResponse += data;
          // 更新当前打字内容
          setCurrentTypingMessage(fullResponse);
          
          // 确保滚动到底部
          if (chatContainerRef.current) {
            chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
          }
        }
      };

      // 处理错误
      eventSource.onerror = (error) => {
        console.error("SSE错误:", error);
        eventSource.close();
        setIsLoading(false);
        setIsTyping(false);
        message.destroy('ai-thinking');
        
        if (!fullResponse) {
          setChatHistory((prev) => [
            ...prev,
            { role: "ai", content: "抱歉，我遇到了一些问题，无法生成回答。" },
          ]);
        } else {
          // 如果已经收到了部分回复，将其添加到聊天历史
          setChatHistory((prev) => [
            ...prev,
            { role: "ai", content: fullResponse },
          ]);
          // 清空当前打字内容
          setCurrentTypingMessage("");
        }
      };

      // 监听结束事件
      eventSource.addEventListener("end", (event) => {
        console.log("收到结束事件");
        eventSource.close();
        setIsLoading(false);
        message.destroy('ai-thinking');
        
        // 打字效果完成，将完整回复添加到聊天历史
        if (fullResponse) {
          console.log("添加AI回复到聊天历史");
          setChatHistory((prev) => [...prev, { role: "ai", content: fullResponse }]);
          // 清空当前打字内容
          setCurrentTypingMessage("");
          setIsTyping(false);
        }
      });
    } catch (error: any) {
      console.error("发送消息出错:", error);
      setIsLoading(false);
      setIsTyping(false);
      message.destroy('ai-thinking');
      message.error("发送失败：" + error.message);
    }
  };

  // 处理输入框回车事件
  const handlePressEnter = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  // 滚动到底部的辅助函数
  const scrollToBottom = () => {
    if (chatContainerRef.current) {
      setTimeout(() => {
        if (chatContainerRef.current) {
          chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
        }
      }, 50);
    }
  };

  // 处理图片删除
  const handleRemoveImage = () => {
    handleImageRemove();
  };

  return (
    <PageContainer
      header={{
        title: "AI 模拟面试",
        ghost: true,
        subTitle: "基于先进AI技术的智能面试助手",
        extra: [
          <div key="tech-info" className="tech-info">
            <span className="tech-pulse"></span>
            AI引擎已就绪
          </div>
        ]
      }}
    >
      <div className="interview-container">
        {/* 科技风格装饰元素 */}
        <div className="tech-lines">
          <div className="tech-line"></div>
          <div className="tech-line"></div>
          <div className="tech-line"></div>
        </div>
        
        {/* 聊天历史区域 */}
        <div className="chat-container" ref={chatContainerRef}>
          {/* 聊天历史消息 */}
          {chatHistory.map((message, index) => (
            <div
              key={index}
              className={`message-bubble ${message.role === "user" ? "user-message" : "ai-message"}`}
            >
              <div className="message-avatar">
                {message.role === "user" ? (
                  <img
                    src={loginUser.userAvatar || "/assets/tech-user-avatar.svg"}
                    alt="用户头像"
                    className="avatar"
                  />
                ) : (
                  <img
                    src="/assets/tech-ai-avatar.svg"
                    alt="AI头像"
                    className="avatar"
                  />
                )}
              </div>
              <div className="message-content">
                {/* 显示用户上传的图片 */}
                {message.role === "user" && message.imageUrl && (
                  <div className="message-image-container">
                    <Image 
                      src={message.imageUrl}
                      alt="用户上传图片"
                      className="message-image"
                      preview={{
                        maskClassName: 'message-image-preview-mask',
                        mask: <div><ExpandOutlined /></div>
                      }}
                    />
                  </div>
                )}
                
                {message.content.split("\n").map((line, i) => (
                  <React.Fragment key={i}>
                    {line}
                    {i < message.content.split("\n").length - 1 && <br />}
                  </React.Fragment>
                ))}
              </div>
            </div>
          ))}
          
          {/* 正在生成的回复 - 作为实时AI消息显示 */}
          {isTyping && currentTypingMessage && (
            <div className="message-bubble ai-message">
              <div className="message-avatar">
                <img
                  src="/assets/tech-ai-avatar.svg"
                  alt="AI头像"
                  className="avatar"
                />
              </div>
              <div className="message-content">
                {currentTypingMessage.split("\n").map((line, i) => (
                  <React.Fragment key={i}>
                    {line}
                    {i < currentTypingMessage.split("\n").length - 1 && <br />}
                  </React.Fragment>
                ))}
                <span className="cursor-blink">|</span>
              </div>
            </div>
          )}
        </div>
        
        {/* 输入区域 - AI回答时禁用输入 */}
        <div className="input-container">
          {/* 图片预览区域 */}
          {previewImage && (
            <div className="image-preview">
              <div className="preview-wrapper">
                <Image 
                  src={previewImage} 
                  alt="预览图片" 
                  className="preview-image"
                  preview={{
                    maskClassName: 'preview-image-mask',
                    mask: <div><ExpandOutlined /></div>
                  }}
                />
                <Button
                  type="text"
                  danger
                  icon={<DeleteOutlined />}
                  className="remove-image-btn"
                  onClick={handleRemoveImage}
                />
              </div>
            </div>
          )}
          
          <Input.TextArea
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            placeholder={isLoading ? "AI正在回复中，请稍候..." : "请输入你想问的问题..."}
            autoSize={{ minRows: 1, maxRows: 4 }}
            onKeyPress={handlePressEnter}
            disabled={isLoading}
            className="tech-input"
          />
          
          <div className="input-actions">
            <ImageUpload 
              onImageUpload={handleImageUpload}
              onImageRemove={handleImageRemove}
              imageUrl={uploadedImageUrl || undefined}
            />
            
            <Button
              type="primary"
              icon={<SendOutlined />}
              onClick={handleSendMessage}
              disabled={isLoading}
              className="send-button"
            >
              发送
            </Button>
          </div>
        </div>
        
        {/* 科技风格页脚 */}
        <div className="interview-footer">
          © 2025 智能面试刷题平台 | AI面试技术支持
        </div>
      </div>
    </PageContainer>
  );
}